<template>
  <div>
    <panel title="物流信息录入">
      <el-form class="form-horizontal" :model="logisticsDto" :rules="logisticsRules" label-width="150px"
               ref="logisticsForm">
        <el-form-item label="日期" prop="backTime">
          <el-input v-model="formatterBackTime" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item v-if="this.type === 3" label="导入文件">
          <el-dropdown @command="handleCommand">
            <el-button type="primary">导入<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <a href="/static/调拨发货导入模板.xlsx" download="调拨发货导入模板.xlsx"
                 style="color:#5a5e66;text-decoration: none ">
                <el-dropdown-item command="handleDownload">模板下载
                </el-dropdown-item>
              </a>
              <el-dropdown-item command="handleImport">数据导入</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
        <el-form-item label="物流公司名称" prop="logisticsCompany">
          <el-select v-model="logisticsDto.logisticsCompany" placeholder="请选择物流公司"
                     prop="logisticsCompany" filterable clearable>
            <el-option
              v-for="item1 in logisticsCompanyList"
              :key="item1.id"
              :label="item1.name"
              :value="item1.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号" prop="logisticsNum">
          <el-input v-model="logisticsDto.logisticsNum" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="logisticsDto.customerName"></el-input>
        </el-form-item>
        <el-form-item label="客户地址">
          <el-input v-model="logisticsDto.customerAddress"></el-input>
        </el-form-item>
        <el-form-item label="客户联系电话">
          <el-input v-model="logisticsDto.customerTel"></el-input>
        </el-form-item>
        <!--v-no-more-click为防止重复提交指令-->
        <el-button type="primary" @click="onBtnFinishWorkOrder()" style="float: right;" v-no-more-click>提交</el-button>
      </el-form>
    </panel>
    <!-- 调拨模板导入模态框 -->
    <el-dialog title="模板导入" :visible.sync="uploadVisible"
               :close-on-click-modal="false" :before-close="uploadCancel">
      <div>
        <el-form label-width="80px" ref="uploadForm" :inline="true">
          <el-form-item style="padding-left: 120px">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="myHeaders"
              name="file"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeAvatarUpload"
              multiple
              drag
              :limit="3"
              :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em><br/>只能上传xlsx文件，且不超过10M</div>
            </el-upload>
          </el-form-item>
          <!--显示导入中错误的数据-->
          <div style="height: 200px;overflow-y: auto" v-if="hideTable">
            <custom-table
              :data="wrongDataList"
              :columns="detailColumns">
            </custom-table>
          </div>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="uploadCancel()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Panel from '@/components/common/Panel'
  import {parseTime} from '@/utils'
  import {apiGetLogisticInfo} from '@/api/repairs/factory/index'
  import {apiGetLogisticsCompanyList} from '@/api/dictionary'
  import {apiLogisticsReadExcel} from '@/api/excel/excelRead'
  import {
    apiGetCustomerLogisticInfo,
    apiPostScrapBack,
    apiGetFactoryLogisticInfo,
    apiPostBadDeviceReturnFactory,
    apiInsertAllotOrder
  } from '@/api/stock/index'
  import store from '@/store'
  import {
    getName,
    getOfficeType,
    getRoleType,
    getOfficeProvinceCode,
    getOfficeCityCode,
    getOutsourceProvinceCode,
    getOutsourceCityCode,
    getOfficeId,
    getUserTel,
    getUserId,
    getOutsourceId
  } from '@/utils/token'
  import {baseInfo} from '@/utils/fetch'
  import {validatePhone} from '@/utils/validation'
  import ElFormItem from '../../../node_modules/element-ui/packages/form/src/form-item.vue'
  import CustomTable from '../../components/table/StockTable.vue'

  export default {
    components: {
      CustomTable,
      ElFormItem,
      Panel
    },
    computed: {
      formatterBackTime () {
        return parseTime(this.logisticsDto.backDay, '{y}-{m}-{d}')
      }
    },
    created () {
      this.logisticsDto.id = this.$route.query.id
      this.type = this.$route.query.type
      if (this.type === 1) {
        // 报废品返还客户
        let listQuery = {
          ystsn: this.$route.query.ystsn
        }
        this.apiGetCustomerLogisticInfo(listQuery)
      } else if (this.type === 2) {
        // 不良品返厂
        let listQuery = {
          id: this.$route.query.factoryId
        }
        this.apiGetFactoryLogisticInfo(listQuery)
      } else if (this.type === 3) {
        // 调拨发货
        this.logisticsDto.customerName = this.$route.query.receiverName
        this.logisticsDto.customerAddress = this.$route.query.receiverAddress
        this.logisticsDto.customerTel = this.$route.query.receiverTel
      }
      this.selectedLogisticsCompanyInit()
    },
    data () {
      return {
        uploadUrl: baseInfo() + '/api/v1/upload',
        myHeaders: {'access_token': store.getters.token},
        // 上传文件显示
        fileList: [],
        type: null,
        // 文件上传路径
        importFileUrl: baseInfo() + '/api/v1/upload',
        // 文件上传参数
        upLoadData: {},
        customer: {
          id: undefined,
          name: '',
          address: '',
          tel: ''
        },
        logisticsCompanyList: [],
        logisticsDto: {
          id: null,
          backDay: new Date().getTime(),
          logisticsNum: '',
          logisticsCompany: '',
          customerName: '',
          customerAddress: '',
          customerTel: '',
          pointId: '',
          pointType: ''
        },
        idArr: [],
        allotOrderDTO: {
          allotId: '',
          idArray: '',
          logisticsNumber: '',
          logisticsCompany: '',
          allotTime: '',
          userId: '',
          operator: '',
          pointId: '',
          num: '',
          pointType: '',
          type: '',
          filePath: undefined
        },
        factoryLogisticsDto: {
          factoryId: null,
          pointId: null,
          pointType: null,
          logisticsNumber: null,
          logisticsCompany: null,
          backTime: new Date().getTime(),
          provinceCode: null,
          cityCode: null,
          senders: null,
          tel: null,
          idsArray: null,
          userId: null,
          ystsn: []
        },
        logisticsRules: {
          logisticsCompany: [
            {required: true, message: '请填写物流公司名', trigger: 'blur'}
          ],
          logisticsNum: [
            {required: true, message: '请填写物流单号', trigger: 'blur'},
            {max: 255, message: '长度不超过 255 个字符', trigger: 'blur'}
          ],
          customerName: [
            {required: true, message: '请填写客户名', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          customerAddress: [
            {required: true, message: '请填写客户地址', trigger: 'blur'},
            {max: 255, message: '长度不得超过255字符', trigger: 'blur'}
          ],
          customerTel: [
            {required: true, message: '请填写客户联系电话', trigger: 'blur'},
            {validator: validatePhone, trigger: 'blur'}
          ]
        },
        uploadVisible: false,
        wrongDataList: [],
        hideTable: false,
        detailColumns: [
          {label: '错误行号', name: 'wrongRowNO', width: '80', height: '40', align: 'center'},
          {label: '错误原因', name: 'reason', height: '40', align: 'center'},
          {label: 'ystsn', name: 'ystsn', height: '40', align: 'center'}],
        listFlag: true
      }
    },
    methods: {
      // 上传成功后的回调
      uploadSuccess (response, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传文件成功'
        })
        this.allotOrderDTO.filePath = response.data
        let filePath = response.data
        this.excelRead(filePath)
        this.fileList = []
        this.fileList.push({name: file.name, url: file.url})
      },
      // 上传错误
      uploadError (err, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传失败，请重试！'
        })
        this.fileList = []
        this.fileList.push({name: file.name, url: file.url})
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload (file) {
        const extension = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension) {
          this.$message({
            showClose: true,
            message: '上传模板只能是 xlsx 格式!'
          })
        }
        if (!isLt2M) {
          this.$message({
            showClose: true,
            message: '上传模板大小不能超过 10MB!'
          })
        }

        return extension && isLt2M
      },
      excelRead (filePath) {
        let listQuery = {
          pointType: '',
          filePath: filePath,
          modelName: this.$route.query.modelName
        }
        if (getRoleType() === '2') {
          listQuery.pointType = 0
          listQuery.pointId = getOfficeId()
        }
        if (getRoleType() === '3') {
          listQuery.pointType = 1
          listQuery.pointId = getOutsourceId()
        }
        apiLogisticsReadExcel(listQuery).then(rsp => {
          if (undefined !== rsp.data) {
            this.wrongDataList = rsp.data.errorDevice
            this.hideTable = true
            this.allotOrderDTO.filePath = ''
          } else {
            this.idArr = rsp.array
            this.hideTable = false
            this.$message({
              showClose: true,
              message: '导入执行中，请稍后!',
              type: 'success'
            })
          }
        })
      },
      handleCommand (command) {
        if (command === 'handleImport') {
          this.dialogType = 'upload'
          this.uploadVisible = true
          this.idArr = []
        } else if (command === 'handleDownload') {
        }
      },
      // 获取工厂快递信息
      apiGetFactoryLogisticInfo (listQuery) {
        apiGetFactoryLogisticInfo(listQuery).then(response => {
          let logistic = response.data
          this.logisticsDto.customerName = logistic.logisticsContact
          this.logisticsDto.customerAddress = logistic.province + logistic.city + logistic.area + logistic.address
          this.logisticsDto.customerTel = logistic.logisticsTel
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 获取客户快递信息
      apiGetCustomerLogisticInfo (listQuery) {
        apiGetCustomerLogisticInfo(listQuery).then(response => {
          let logistic = response.data
          this.logisticsDto.customerName = logistic.customerName
          this.logisticsDto.customerAddress = logistic.address
          this.logisticsDto.customerTel = logistic.tel
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      selectedLogisticsCompanyInit () {
        apiGetLogisticsCompanyList().then(response => {
          let logisticsCompanyList = response.data
          let logisticsCompany = []
          let temp = {}
          for (let i in logisticsCompanyList) {
            if (!temp[logisticsCompanyList[i].name]) {
              temp[logisticsCompanyList[i].name] = logisticsCompanyList[i].id
            }
          }
          for (let k in temp) {
            logisticsCompany.push({'name': k, 'id': temp[k]})
          }
          this.logisticsCompanyList = logisticsCompany
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      apiGetLogisticInfo () {
        apiGetLogisticInfo(this.batch).then(response => {
          let logistic = response.data
          this.logisticsDto.customerName = logistic.contact
          this.logisticsDto.province = logistic.province
          this.logisticsDto.provinceCode = logistic.provinceCode
          this.logisticsDto.city = logistic.city
          this.logisticsDto.cityCode = logistic.cityCode
          this.logisticsDto.customerTel = logistic.tel
          this.logisticsDto.customerAddress = logistic.address
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      onBtnFinishWorkOrder () {
        this.$refs['logisticsForm'].validate((valid) => {
          if (valid) {
            let type = this.$route.query.type
            if (type === 1) { // 报废品返还客户
              if (getRoleType() === '2') { // 办事处权限
                this.logisticsDto.pointType = 0
                this.logisticsDto.pointId = getOfficeId()
              } else { // 外包商权限
                this.logisticsDto.pointType = 1
                this.logisticsDto.pointId = getOutsourceId()
              }
              apiPostScrapBack(this.logisticsDto).then(() => {
                this.$message({
                  showClose: true,
                  message: '提交成功',
                  type: 'success'
                })
                this.$router.push({
                  path: '/stock/scrappage'
                })
              }).catch(() => {
                this.tableLoadingFlag = false
              })
            } else if (type === 2) { // 不良品返厂
              this.factoryLogisticsDto.factoryId = this.$route.query.factoryId
              this.factoryLogisticsDto.idsArray = this.$route.query.idArrays
              this.factoryLogisticsDto.logisticsCompany = this.logisticsDto.logisticsCompany
              this.factoryLogisticsDto.logisticsNumber = this.logisticsDto.logisticsNum
              this.factoryLogisticsDto.senders = getName()
              this.factoryLogisticsDto.userId = getUserId()
              this.factoryLogisticsDto.tel = getUserTel()
              this.factoryLogisticsDto.ystsn = this.$route.query.ystsn
              if (getRoleType() === '2') { // 办事处权限
                this.factoryLogisticsDto.pointType = 0
                this.factoryLogisticsDto.pointId = getOfficeId()
                this.factoryLogisticsDto.provinceCode = getOfficeProvinceCode()
                this.factoryLogisticsDto.cityCode = getOfficeCityCode()
              } else { // 外包商权限
                this.factoryLogisticsDto.pointType = 1
                this.factoryLogisticsDto.pointId = getOutsourceId()
                this.factoryLogisticsDto.provinceCode = getOutsourceProvinceCode()
                this.factoryLogisticsDto.cityCode = getOutsourceCityCode()
              }
              apiPostBadDeviceReturnFactory(this.factoryLogisticsDto).then(() => {
                this.$message({
                  showClose: true,
                  message: '提交成功',
                  type: 'success'
                })
                this.$router.push({
                  path: '/stock/bad/factory'
                })
              }).catch(() => {
                this.tableLoadingFlag = false
              })
            } else if (type === 3) { // 调拨发货
              this.allotOrderDTO.allotId = this.$route.query.id
              this.allotOrderDTO.allotTime = new Date().getTime()
              this.allotOrderDTO.idArray = this.idArr
              this.allotOrderDTO.logisticsCompany = this.logisticsDto.logisticsCompany
              this.allotOrderDTO.logisticsNumber = this.logisticsDto.logisticsNum
              this.allotOrderDTO.operator = getName()
              this.allotOrderDTO.userId = getUserId()
              this.allotOrderDTO.num = this.idArr.length
              this.allotOrderDTO.type = 1
              if (getRoleType() === '2') { // 办事处权限
                this.allotOrderDTO.pointType = 0
                this.allotOrderDTO.pointId = getOfficeId()
              } else { // 外包商权限
                this.allotOrderDTO.pointType = 1
                this.allotOrderDTO.pointId = getOutsourceId()
              }
              if (this.allotOrderDTO.filePath === undefined) {
                this.$message({
                  showClose: true,
                  message: '请导入文件',
                  type: 'error'
                })
                return false
              } else if (this.allotOrderDTO.filePath === '') {
                this.$message({
                  showClose: true,
                  message: '请重新导入文件',
                  type: 'error'
                })
                return false
              }
              apiInsertAllotOrder(this.allotOrderDTO).then(rsp => {
                if (rsp.resCode === '200') {
                  this.$message({
                    showClose: true,
                    message: '提交成功',
                    type: 'success'
                  })
                  this.$refs['logisticsForm'].resetFields()
                  this.allotOrderDTO.filePath = ''
                  this.idArr = []
                }
                this.$router.push({
                  path: '/stock/good/allocate'
                })
              }).catch(() => {
                this.tableLoadingFlag = false
              })
            }
          } else {
            return false
          }
        })
      },
      uploadCancel () {
        this.uploadVisible = false
        this.wrongDataList = []
        this.fileList = []
        this.hideTable = false
        this.$refs['uploadForm'].resetFields()
      }
    }
  }
</script>
